package com.example.learn_spring_boot3.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.learn_spring_boot3.utils.ResponseData;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequestMapping("http")
public class HttpController {
    /**
     * get 请求
     */
    @GetMapping("get")
    public ResponseEntity<ResponseData> get() {
        HashMap<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("name", "test");
        paramsMap.put("age", 18);
        String s = HttpUtil.get("http://localhost:8100/test/1", paramsMap, 30 * 1000);
        JSON response = JSONUtil.parse(s);
        return ResponseEntity.ok(ResponseData.success(response));
    }


    /**
     * post 请求
     */
    @PostMapping("post")
    public ResponseEntity<ResponseData> post() {
        HashMap<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("bodyName", "test1");
        bodyMap.put("age", 1);
        bodyMap.put("file", FileUtil.file("C:\\Users\\33153\\Desktop\\test.png")); // 上传成file

        String s = HttpUtil.post("http://localhost:8100", bodyMap, 30 * 1000);
        JSON response = JSONUtil.parse(s);
        return ResponseEntity.ok(ResponseData.success(response));
    }

    /**
     * 自定义构造请求
     */
    @PostMapping("custom")
    public ResponseEntity<ResponseData> custom() {
        HttpResponse execute = HttpUtil.createPost("http://localhost:8100") // 创建post请求
                .form("name", "test") // 如果post就是body的值, 如果是get则会拼接到地址栏 ? 后面
                .form("file", FileUtil.file("C:\\Users\\33153\\Desktop\\test.png")) // post时会上传成file, get则是普通参数
                .header("My-Header", "test") // 请求头
                .timeout(30 * 1000) // 超时时间, 毫秒
                .cookie("test cookie") // 设置 cookie
                .execute();

        // JSON反序列化响应体数据
        JSON bodyObj = JSONUtil.parse(execute.body());
        return ResponseEntity.ok(ResponseData.success(bodyObj));
    }
}
